//
//  ZYUserAccount.swift
//  weibo007
//
//  Created by 陈宗毅 on 15/12/19.
//  Copyright © 2015年 czy. All rights reserved.
//

import UIKit

class ZYUserAccount: NSObject,NSCoding {
    
    
    class var userLogin: Bool
    {
        return ZYUserAccount.loadUserAccount() != nil
    }

    var access_token: String?
    
    var uid: String?
    
    var expires_in:NSTimeInterval = 0 {
        didSet {
            expires_Date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    //过期时间
    var expires_Date:NSDate?
    ///用户昵称
    var screen_name:String?
    ///用户头像地址
    var avatar_large: String?
    
    
    //字典转模型
    init(dict:[String:AnyObject])
    {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    //3.当字典的key在模型里面找不到属性的时候会调用
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    //打印对象内容
   override var description: String{
        get {
            return "access_token:\(access_token),uid:\(uid),expires_in:\(expires_in),expires_Date:\(expires_Date)"
        }
    }
    
    //加载用户数据
    func loadUserInfo(finished: (error:NSError?) -> ()){
        // 调用网络工具类的方法来加载用户信息,准备一个闭包
        ZYNetworkTool.shareInstance.loadUserInfo { (result, error) -> () in
            //判断是否有错误
            if error != nil || result == nil {
                print("获取用户数据有错误：\(error)")
                finished(error: error)
                return
            }
            
            self.screen_name = result!["screen_name"] as? String
            self.avatar_large = result!["avatar_large"]as?String
            // 对象更新了内容.
            // 1.将最新的对象保存到沙盒
            self.saveUserAccount()
            // 2.将最新的对象(self)赋值给属性 CZUserAccount.userAccount
            // userAccount是一个类属性,需要使用类名.属性名来访问
            ZYUserAccount.userAccount = self
            
            finished(error: nil)
        }
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    
    //解档
    required init?(coder aDecoder: NSCoder) {
      access_token  =  aDecoder.decodeObjectForKey("access_token")as? String
        uid = aDecoder.decodeObjectForKey("uid")as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_Date = aDecoder.decodeObjectForKey("expires_Date")as?NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    //获取沙盒路径
    //拼接文件名
    static let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
    
    // 使用归档和接档
    /// 保存账户信息
    func saveUserAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: ZYUserAccount.path)
    }
    
    static var userAccount: ZYUserAccount?
    
    // 程序一开始没有账号需要解档.写成类方法
    // 用户账户信息不一定存在,没有登陆,AccessToken过期了
   class func loadUserAccount() -> ZYUserAccount?{
    
    if userAccount == nil
    {
        userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ZYUserAccount
    }
    
    if userAccount != nil && userAccount?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
        print("加载到可用账号")
        
        return userAccount
    }
    
    return nil
    
    
    
        //解档
        //获取账户信息路径
//    if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path)as? ZYUserAccount{
//        if userAccount.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
//            //没有过期，账号可用
//            print("加载到可用账号")
//            return userAccount
//        }else
//        {
//            print("账号过期")
//            return nil
//        }
//    }else {
//        print("没有加载到账号")
//    }
//    
//    return nil
    
        
    }
}
